package org.racsor.cc.action;

import java.net.URL;
import java.util.List;
import java.util.logging.Logger;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.racsor.cc.model.RequestCC;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class ProcessRequestCC {
    private static final Logger log = Logger.getLogger(ProcessRequestCC.class.getName());
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    String content = "application/x-amf";
    URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();

    public void doProcess(RequestCC requestcc) {

	try {

	    log.warning("url:" + requestcc.toString());

	    byte[] xurro = blobstoreService.fetchData(requestcc.getBlob(), 0, requestcc.getSize());

	    URL url = new URL(requestcc.getUrl() + "?" + requestcc.getParameters());

	    HTTPRequest reqredirect = new HTTPRequest(url, HTTPMethod.POST);
	    if (!StringUtils.isEmpty(requestcc.getCookies())) {
		reqredirect.setHeader(new HTTPHeader("Cookie", requestcc.getCookies()));
	    }
	    reqredirect.setHeader(new HTTPHeader("Connection", "keep-alive"));
	    reqredirect.setHeader(new HTTPHeader("Content-Type", content));
	    reqredirect.setPayload(xurro);

	    HTTPResponse fetchresp = fetcher.fetch(reqredirect);

	    log.warning("responsecode:" + fetchresp.getResponseCode());

	    List<HTTPHeader> headers = fetchresp.getHeaders();

	    for (HTTPHeader header : headers) {
		String headerName = header.getName();
		String headerValue = header.getValue();
		log.warning("headerName:" + headerName + ":headerValue:" + headerValue);
		if (StringUtils.startsWithIgnoreCase(headerName, "set-cookie")) {
		    log.warning("setCookie:" + headerValue);
		    requestcc.setCookies(headerValue);
		}
	    }

	    log.warning("content:" + new String(fetchresp.getContent()));
	} catch (Exception e) {
	    log.warning(ExceptionUtils.getStackTrace(e));
	}

    }

}
